package com.yz.jdd.module.main;

import static com.yunzong.iot.config.IotConfig.CODE;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gyf.barlibrary.ImmersionBar;
import com.igexin.sdk.PushManager;
import com.trello.rxlifecycle.ActivityEvent;
import com.yunzong.iot.auth.Auth;
import com.yunzong.iot.http.RequestClient;
import com.yunzong.iot.http.RequestProxy;
import com.yunzong.iot.http.request.RequestAuth;
import com.yunzong.iot.http.response.ResponseBase;
import com.yunzong.iot.service.HeartBeatService;
import com.yunzong.iot.utils.encrypt.SecureUtils;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.StringUtil;
import com.yz.jdd.module.launch.view.LaunchActivity;
import com.yz.jdd.module.main.entity.HuabeiService;
import com.yz.jdd.module.main.entity.MenuInfoBean;
import com.yz.jdd.module.main.fragment.H5Fragment;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_PayShopInfo;
import com.yz.jdd.network.response.Response_PayShopInfo;
import com.yz.jdd.receiver.DemoIntentService;
import com.yz.jdd.receiver.DemoPushService;
import com.yz.jdd.voice.SpeechUtilOffline;
import com.yz.jdd.webview.HostJsScope;
import com.yz.jdd.webview.Router;
import com.yz.jdd.webview.download.H5DownFileUtils;
import com.yz.jdd.webview.entity.MsgCountBean;
import com.yz.jdd.widget.AdDialog;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;

import java.lang.reflect.Method;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActivity  {

    private TextView messageCount;

    private FloatingActionButton fab_setting;

    private final static int NOTIFICATION_ID_ICON = 0x10000;

    public static BaseActivity mainActivityObj;

    private MyReceiver receiver;
    private IntentFilter intentFilter;
    AdDialog adDialog;

    public MenuInfoBean menuInfoBean;
    private List<List<MenuInfoBean.ConfigBean>> menuLists;
    StringBuilder menuStringBuilder = new StringBuilder();
    private BottomNavigationView bottomNav;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .reset()  //重置所以沉浸式参数
                .transparentStatusBar()  //透明状态栏，不写默认透明色
                .statusBarColor(R.color.color_ffffff)     //状态栏颜色，不写默认透明色
                .statusBarDarkFont(true, 0.01f)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.color_030C1A)  //修改flyme OS状态栏字体颜色
                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色
                .supportActionBar(false) //支持ActionBar使用
                .addTag("tag")  //给以上设置的参数打标记
                .getTag("tag")  //根据tag获得沉浸式参数
                .init();
        addIconToStatusBar(R.drawable.icon);
        if (LaunchActivity.instance != null) {
            LaunchActivity.instance.finish();
            LaunchActivity.instance = null;
        }

        setContentView(R.layout.activity_main_tab);
        initWidget(savedInstanceState);
        getPhonePermissions();
        String code = PreferencesUtils.getString(MainActivity.this, BaseConfigs.STRING_MOVEKOUBEI, "0");
        //加一个判断以免频繁调用
        if ("0".equals(code)) {
            getMoveKoubei();
        }
        getMsgCount();
        getOrderCondition();
        getPayShopInfo();
        mainActivityObj = this;
        receiver = new MyReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("updateNativePage");
        registerReceiver(receiver, intentFilter);
        authIot();
        RxBus.with(this).setEvent(Events.EVENT_HIDE_SHOW_BOTTOM_NAV).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events.getContent()){
                    bottomNav.setVisibility(View.VISIBLE);
                }else {
                    bottomNav.setVisibility(View.GONE);
                }

            }
        }).create();
    }

    private String getMenusParams() {
        String menu = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_MENUINFO, "");
        if (!TextUtils.isEmpty(menu)) {
            menuInfoBean = new Gson().fromJson(menu, MenuInfoBean.class);
            if (menuInfoBean != null) {
                menuLists = menuInfoBean.tab3.menuList;
                if (menuLists == null || menuLists.size() == 0) {
                    return "";
                }
                for (List<MenuInfoBean.ConfigBean> configBeanList : menuLists) {
                    if (configBeanList != null && configBeanList.size() > 0) {
                        int size = configBeanList.size();
                        for (int i = 0; i < size; i++) {
                            String module = configBeanList.get(i).moduleName + "";
                            Log.e("lkf", " module=" + module);
                            menuStringBuilder.append(module).append(",");
                        }
                    }
                }
                if (menuStringBuilder.length() > 0) {
                    menuStringBuilder.deleteCharAt(menuStringBuilder.length() - 1);
                }
            }
        }
        return menuStringBuilder.toString();
    }

    /**
     * 查询默认支付门店
     */
    private void getPayShopInfo() {
        Request_PayShopInfo request_payShopInfo = new Request_PayShopInfo();
        request_payShopInfo.setType("app_pay");
        NetWorkRequset.getPayShopInfo(request_payShopInfo, new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                Response_PayShopInfo responsePayShopInfo = (Response_PayShopInfo) response_baseModel.getResultObject();
                if (responsePayShopInfo != null) {
                    String shopId = responsePayShopInfo.getShopId();
                    String shopName = responsePayShopInfo.getShopName();
                    int shopNum = responsePayShopInfo.getShopNum();
                    List<String> payTypes = responsePayShopInfo.getPayTypes();
                    if (!TextUtils.isEmpty(shopName)) {
                        PreferencesUtils.putString(MainActivity.this, BaseConfigs.PREF_CASH_SHOPNAME, shopName);
                    }
                    if (!TextUtils.isEmpty(shopId)) {
                        PreferencesUtils.putString(MainActivity.this, BaseConfigs.PREF_CASH_SHOPID, shopId);
                    }
                    PreferencesUtils.putInt(MainActivity.this, BaseConfigs.PREF_CASH_SHOPNUM, shopNum);

                    if (payTypes != null && payTypes.size() > 0) {
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = payTypes.size() - 1; i >= 0; i--) {
                            stringBuilder.append(payTypes.get(i)).append("#");
                        }
                        PreferencesUtils.putString(MainActivity.this, BaseConfigs.PREF_CASH_PAYTYPES, stringBuilder.toString());
                    }
                    HuabeiService huabeiService = responsePayShopInfo.getHuabeiService();
                    if (huabeiService != null && huabeiService.getHUABEI_AMORTIZE() != null && huabeiService.getHUABEI_AMORTIZE().size() > 0) {
                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREFS_STR_EXTINFO, new Gson().toJson(huabeiService));
                    }
                }
            }

            @Override
            public void onNeedLogin(String msg) {

            }
            @Override
            public void onFail(Response_Base response_baseModel) {

            }
        });
    }

    private void getPhonePermissions() {
        XXPermissions.with(MainActivity.this)
                //.constantRequest() //可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .permission(Permission.READ_PHONE_STATE
                ) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        dismissTopDialog();
                        //必要权限
                        if (granted.contains(Permission.READ_PHONE_STATE)) {
                            try {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        SpeechUtilOffline.getInstance(getApplicationContext());
                                    }
                                }).start();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            permissionDialog();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        dismissTopDialog();
                        if (quick) {
                            showToast("被永久拒绝授权，请手动授予权限");
                            if (denied.contains(Permission.READ_PHONE_STATE)) {
                                permissionDialog();
                            }
                        }
                    }

                });
        if (!XXPermissions.isHasPermission(MainActivity.this, Permission.READ_PHONE_STATE)) {
            showTopDialog("为了您能正常使用【语音播报】功能，需向您申请获取手机状态(IMEI）的权限。如果拒绝，您将无法使用语音播报功能，其他功能可正常使用。");
        }

    }

    //未授权权限弹出对话框
    public void permissionDialog() {
        final PublicDialog permission = new PublicDialog(MainActivity.this);
        permission.setTitle("请开启相关权限");
        permission.setMessage("为保证扫码收款功能正常使用，请务必开启相机权限!");
        permission.setRightBtn("去设置", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                XXPermissions.gotoPermissionSettings(MainActivity.this);
                permission.dismiss();
            }
        });
        permission.setLeftBtn("取消", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                permission.dismiss();
                MainActivity.this.finish();
            }
        });
        permission.setCancelable(false);
        permission.show();

    }

    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(this);
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    private void authIot() {
        RequestAuth requestAuth = new RequestAuth();
        String guid = PreferencesUtils.getString(this, BaseConfigs.STRING_GUID);
        requestAuth.setSn(guid);
        requestAuth.setUuid(guid);
        String gsonStr = new Gson().toJson(requestAuth);
        String requestAuthStr = SecureUtils.encode3Des(CODE, gsonStr);
        RequestClient.getInstance().buildRetrofit("");
        RequestProxy.doAuth(requestAuthStr)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBase<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBase<String> response) {
                        String backStr = response.getData();
                        String authJson = SecureUtils.decode3Des(CODE, backStr);
                        Auth auth = new Gson().fromJson(authJson, Auth.class);
                        Intent intent = new Intent(MainActivity.this, HeartBeatService.class);
                        intent.putExtra("auth", auth);
                        startService(intent);
                    }
                });

    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content = intent.getStringExtra("page");
            if (!StringUtil.isEmpty(content)) {
                if ("newsPage".equals(content)) {
                    // 代办消息刷新
                    getMsgCount();
                }
            }
        }
    }

    /**
     * 获取是否已经去口碑化
     */
    private void getMoveKoubei() {
        NetWorkRequset.doCheckMoveKoubei(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                String code = (String) response_baseModel.getResultObject();
                // 1-不弹框  0-弹框

                if ("1".equals(code)) {
                    PreferencesUtils.putString(MainActivity.this, BaseConfigs.STRING_MOVEKOUBEI, code);
                } else {
                    showMoveKoubei();
                }
            }

            @Override
            public void onNeedLogin(String msg) {

            }

            @Override
            public void onFail(Response_Base response_baseModel) {

            }
        });
    }

    /**
     * 获取订单筛选条件
     */
    private void getOrderCondition() {
        NetWorkRequset.doOrderCondition(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                if (response_baseModel.getCode().equals("1")) {
                    String jsonStr = new Gson().toJson(response_baseModel.getResultObject());
                    PreferencesUtils.putString(MainActivity.this, BaseConfigs.STRING_ORDER_CONDITION, jsonStr);
                }
            }

            @Override
            public void onNeedLogin(String msg) {
            }

            @Override
            public void onFail(Response_Base response_baseModel) {
            }
        });
    }

    /**
     * 获取未读消息数量
     */
    private void getMsgCount() {

        NetWorkRequset.doMsgCount(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                try {
//                消息类型：0待办事项，1通知公告，2系统消息
                    String jsonStr = new Gson().toJson(response_baseModel.getResultObject());
                    PreferencesUtils.putString(MainActivity.this, BaseConfigs.PREF_MSG_COUNT, jsonStr);
                    MsgCountBean msgCountBean = new Gson().fromJson(jsonStr, MsgCountBean.class);
                    int count = msgCountBean.getTotalCount();
                    if (count > 0) {
                        messageCount.setVisibility(View.VISIBLE);
                    } else {
                        messageCount.setVisibility(View.GONE);
                    }
                    RxBus.getInstance().send(Events.EVENT_BACKLOG_RESPONSE, jsonStr);
                } catch (Exception e) {
                    LogUtils.i("ljm" + e.toString());
                }

            }

            @Override
            public void onNeedLogin(String msg) {

            }

            @Override
            public void onFail(Response_Base response_baseModel) {

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addCategory(Intent.CATEGORY_HOME);
                startActivity(home);
                return true;
            }
        }


        return super.onKeyDown(keyCode, event);
    }

    /**
     * 展示对话框
     */
    private void showMoveKoubei() {

        final PublicDialog movekoubei = new PublicDialog(this);
        movekoubei.setTitle("服务调整通知");
        movekoubei.setMessage("尊敬的商家：\n\t\t感谢您一直以来对同福的信任和支持。因相关合作伙伴合作到期，" +
                "同福产品部分服务功能进行调整，即日起同福产品部分功能将停止使用，为了向您提供更优质的服务，" +
                "现就涉及调整的服务推出<a href=\"vuepages/index.html#/ServiceAdjustmentAgreement\">《服务调整协议》</a>。" +
                "请您务必仔细阅读并透彻理解协议内容，在确认充分理解后点击同意，" +
                "点击同意后即代表您已阅读并同意<a href=\"vuepages/index.html#/ServiceAdjustmentAgreement\">" +
                "《服务调整协议》</a>。\n\t\t产品功能调整详见<a href=\"vuepages/index.html#/ServiceAdjustmentContent\">《服务调整内容》</a>" +
                "，由此给您带来的不便，敬请谅解。如有疑问，请致电官方客服热线400-109-9960。\n\t\t再次感谢您对同福的关注和支持，" +
                "我们将继续竭诚为您提供优质、便捷的服务！", false);
        movekoubei.setRightBtn("同意", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                NetWorkRequset.doConfirmMoveKoubei(new MySubscriber() {
                    @Override
                    public void onSuccess(Response_Base response_baseModel) {

                    }

                    @Override
                    public void onNeedLogin(String msg) {

                    }

                    @Override
                    public void onFail(Response_Base response_baseModel) {

                    }
                });
                movekoubei.dismiss();


            }
        });

        movekoubei.setCancelable(true);
        movekoubei.show();

    }

    /**
     * 展示广告弹窗
     *
     * @param
     */
    private void showAlertAd() {
        String menu = PreferencesUtils.getString(MyApplication.application,
                BaseConfigs.PREF_MENUINFO, "");
        MenuInfoBean menuInfoBean = new Gson().fromJson(menu, MenuInfoBean.class);

        if (menuInfoBean != null) {
            if (menuInfoBean.tab0 != null && menuInfoBean.tab0.alertAd != null
                    && menuInfoBean.tab0.alertAd.adMenuItems != null &&
                    menuInfoBean.tab0.alertAd.adMenuItems.size() > 0) {
                List<MenuInfoBean.ConfigBean> alertAdList = menuInfoBean.tab0.alertAd.adMenuItems;

                //获取历史事件
                long lastShowTime = PreferencesUtils.getLong(MyApplication.application,
                        BaseConfigs.PREF_LONG_DIALOG_PERIOD, 0L);
                long nowTime = System.currentTimeMillis();
                long howLongTime = nowTime - lastShowTime;
                int defaultPeriod = 24;
                if (menuInfoBean.tab0.alertAd.period > 0) {
                    defaultPeriod = menuInfoBean.tab0.alertAd.period;
                }

                boolean isShow = false;
                String md5Old = PreferencesUtils.getString(MyApplication.application,
                        BaseConfigs.PREF_STRING_DIALOG_ADMD5, "");

                String md5New = menuInfoBean.tab0.alertAd.id;
                if (!md5Old.equals(md5New)) {
                    isShow = true;
                    PreferencesUtils.putString(MyApplication.application,
                            BaseConfigs.PREF_STRING_DIALOG_ADMD5, md5New);
                }
                if (howLongTime - defaultPeriod * 60 * 60 * 1000 >= 0) {
                    isShow = true;
                }
                if (isShow) {
                    PreferencesUtils.putLong(MyApplication.application,
                            BaseConfigs.PREF_LONG_DIALOG_PERIOD, nowTime);
                    if (adDialog != null && adDialog.isShowing()) {
                        return;
                    }
                    adDialog = new AdDialog(MainActivity.this, alertAdList);
                    adDialog.show();
                }


            }
        }
    }

    private void initWidget(Bundle savedInstanceState) {
         bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);
        bottomNav.setItemIconTintList(null);
        bottomNav.setSelectedItemId(R.id.nav_home);
        bottomNav.setItemTextAppearanceActive(R.style.bottom_selected_text);
        bottomNav.setItemTextAppearanceInactive(R.style.bottom_normal_text);
        messageCount = (TextView) findViewById(R.id.tv_message_count);
        // 注册待办消息变动监听
        RxBus.with(this).
                setEvent(Events.EVENT_BACKLOG_CHANGE).
                setEndEvent(ActivityEvent.DESTROY).
                onNext(new Action1<Events<?>>() {
                    @Override
                    public void call(Events<?> events) {
                        getMsgCount();
                    }
                }).
                create();
    }

    private final BottomNavigationView.OnNavigationItemSelectedListener navListener =
            menuItem -> {
                Bundle args = new Bundle(); // 创建Bundle用于传递参数
                String mainUrl = "";
                Fragment selectedFragment = null;
                switch (menuItem.getItemId()) {
                    case R.id.nav_home:
                        args = new Bundle();
                        mainUrl = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + Router.home_url + Router.getCommonParam();
                        args.putString(Constants.H5_WEB_URL, mainUrl);
                        selectedFragment = new H5Fragment();
                        break;
                    case R.id.nav_digitization:
                        selectedFragment = new H5Fragment();
                        args = new Bundle();
                        mainUrl = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + Router.digitization_url + Router.getCommonParam();
                        args.putString(Constants.H5_WEB_URL, mainUrl);
                        break;
                    case R.id.nav_finance:
                        selectedFragment = new H5Fragment();
                        args = new Bundle();
                        mainUrl= "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + Router.finance_url + Router.getCommonParam();
                        args.putString(Constants.H5_WEB_URL, mainUrl);
                        break;
                    case R.id.nav_user:
                        selectedFragment = new H5Fragment();
                        args = new Bundle();
                        mainUrl = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + Router.my_url + Router.getCommonParam() + "&menuList=" + getMenusParams();
                        args.putString(Constants.H5_WEB_URL, mainUrl);
                        break;
                }
                selectedFragment.setArguments(args);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();
                return true;
            };


    @Override
    protected void onResume() {
        super.onResume();
        Log.e("lkf", "0000000");
        //初始化个推
        PushManager.getInstance().initialize(MyApplication.application, DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(MyApplication.application, DemoIntentService.class);
        showAlertAd();


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("lkf", "0000000");
    }

    @Override
    protected void onDestroy() {

        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        deleteIconToStatusbar();
        stopService(new Intent(this, HeartBeatService.class));
        super.onDestroy();
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 如果没有从状态栏中删除ICON，且继续调用addIconToStatusbar,则不会有任何变化.如果将notification中的resId设置不同的图标，
     * 则会显示不同的图标
     */
    private void addIconToStatusBar(int resId) {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n;

        Intent intent = new Intent(this, JumpActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

        if (Build.VERSION.SDK_INT < 16) {
            n = new Notification();
            Class clazz = n.getClass();
            try {
                Method m2 = clazz.getDeclaredMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);
                m2.invoke(n, this, getString(R.string.app_name),
                        getString(R.string.app_open), pi);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel("yunzong", "商家app",
                        NotificationManager.IMPORTANCE_LOW);
                nm.createNotificationChannel(mChannel);
                n = new Notification.Builder(this)
                        .setChannelId("yunzong")
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(getString(R.string.app_open))
                        .setSmallIcon(resId).build();
            } else {
                n = new Notification.Builder(this)
                        .setAutoCancel(false)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(getString(R.string.app_open))
                        .setContentIntent(pi)
                        .setSmallIcon(resId)
                        .setWhen(System.currentTimeMillis())
                        .build();
            }
        }
        n.contentIntent = pi;
        //常驻状态栏的图标
        n.icon = resId;
        // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
        n.flags |= Notification.FLAG_ONGOING_EVENT;
        // 表明在点击了通知栏中的"清除通知"后，此通知不清除，经常与FLAG_ONGOING_EVENT一起使用
        n.flags |= Notification.FLAG_NO_CLEAR;
        nm.notify(NOTIFICATION_ID_ICON, n);

    }

    private void deleteIconToStatusbar() {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(NOTIFICATION_ID_ICON);
    }
}
